<?php

/******************************************************
 *					  	 CONFIG					      *
 ******************************************************/

/**
 * Checks if configuration parameter is defined on the database
 * @param string $param
 * @return boolean 
 * @author Pablo
 * @since 1.0
 */
function blg_db_config_param_exists($param){
	$query= blg_dbschema_select_config(array('param' => $param));
	$query= blg_dbschema_query_buid($query, 'count');
	$result= blg_dbschema_select($query);
	$result= (int)$result->{0}['result'];
	return ($result>0);	
}

/**
 * Select a configuration parameter from the database
 * @param string $param
 * @return mixed Returns the value found on database, NULL otherwise
 * @author Pablo
 * @since 1.0
 */
function blg_get_db_config($param){
	$result= blg_dbschema_select(blg_dbschema_query_buid(blg_dbschema_select_config(
		array('param' => $param),
		array('value')
	)));		

	return ($result->success && $result->num_rows>0)?$result->{0}['value']:NULL;
}

/**
 * Updates a configuration parameter value int the database if parameter exists
 * @param string $param
 * @return boolean Returns true if the parameter exists and was updated, FALSE otherwise.
 * @author Pablo
 * @since 1.0
 */
function blg_set_db_config($param, $value){
	if(blg_db_config_param_exists($param)){
		$query= blg_dbschema_query_buid(blg_dbschema_update_config(
			array('param' => $param),
			array('value' => $value)
		));
		$result= blg_dbschema_update($query);
		return $result->success;		
	}

	return FALSE;
}

/**
 * Get a configuration param
 * @param $name
 * @return mixed The param value if exists, NULL if not
 * @author Pablo
 * @since 1.0
 */
function blg_get_config($name){
	global $_CONFIG;
	
	if(isset($_CONFIG->$name))
		return $_CONFIG->$name;		
		
	if(NULL!==($value=blg_get_db_config($name)))
		return $value;

	return NULL;
}

/**
 * Set a configuration param
 * @param $name
 * @param $value 
 * @author Pablo
 * @since 1.0
 */
function blg_set_config($name, $value){
	global $_CONFIG;
	
	if(blg_db_config_param_exists($name))
		blg_set_db_config($name, $value);
	
	$_CONFIG->$name= $value;	
}

/**
 * Load configuration from database
 * @author Pablo
 * @since 1.0
 */
function blg_load_db_config(){	
	$result= blg_dbschema_select(blg_dbschema_query_buid(blg_dbschema_select_config()));
	
	for($i=0; $i<$result->num_rows; $i++){
		$param= $result->{$i}['param'];
		$value= $result->{$i}['value'];
		blg_set_config($param, $value);
	}	
}